package com.ruoyi.smart.chat;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.smart.entity.Message;
import com.ruoyi.smart.entity.MessageDb;
import com.ruoyi.smart.entity.Result;
import com.ruoyi.smart.entity.StatusCode;
import com.ruoyi.smart.robot.RobotApi;
import com.ruoyi.smart.service.SmartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;



@ServerEndpoint("/webSocket/{username}")
@Component
public class Chat {

//    private static ApplicationContext applicationContext;
//
//    public static void setApplicationContext(ApplicationContext context) {
//        applicationContext = context;
//    }
//
//    applicationContext.getBean()
     private static   SmartService smartService;

    @Autowired
    public void setChatService(SmartService smartService) {
        Chat.smartService = smartService;
    }

    private static MessageDb messageDb = new MessageDb();

    private static StringBuilder messageRecord = new StringBuilder();



//    @Autowired
//    private  RobotApi robotApi;

    private static   RobotApi robotApi;

    @Autowired
    public void setRobotApi(RobotApi robotApi) {
        Chat.robotApi = robotApi;
    }



    private static int onlineCount = 0;
    private static Map<String, Chat> clients = new ConcurrentHashMap<String, Chat>();
    private Session session;
    private String username;


    /**
     * 建立链接
     * @param username
     * @param session
     * @throws IOException
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {
        this.username = username;
        this.session = session;
        Chat.onlineCount++;
        clients.put(username, this);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageDb.setCreateDate(sdf.format(new Date()));
        /**
         * 发送除了自己所有的用户名字
         */
        for (String user : clients.keySet()) {
            List<String> list=new ArrayList();
            for (String s : clients.keySet()) {
                if (!s.equals(user)){
                    list.add(s);
                }
            }
            clients.get(user).session.getBasicRemote().sendText(JsonMessage(false,null,list));
        }
    }


    /**
     * 关闭链接时，删除在线用户
     */
    @OnClose
    public void onClose() {
        clients.remove(username);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        messageDb.setLastDate(sdf.format(new Date()));
        messageDb.setMessage(messageRecord.toString());
        smartService.insert(messageDb);
        MessageDb messageDb1 = new MessageDb();
        messageDb =messageDb1;
        messageRecord.replace(0,messageRecord.length(), "");

        Chat.onlineCount--;
    }


    /**
     * 消息发送
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        Message message1 = JSON.parseObject(message, Message.class);
        Set<String> strings = clients.keySet();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        /**
         * 如果接收的人存在就发送
         */
        if (strings.contains(message1.getToName())){
            if (message1.getFromName().equals(message1.getToName())){
                Message toMessage = new Message();


                String robotResult = robotApi.getRobotResult(message1.getMessage());
                JSONObject jsonobj = JSON.parseObject(robotResult);
                JSONArray result = jsonobj.getJSONArray("results");
                for (int i = 0; i < result.size(); i++) {
                    toMessage.setMessage(result.getJSONObject(0).getJSONObject("values").getString("text"));
                }



                toMessage.setToName(message1.getFromName());
                toMessage.setFromName(message1.getFromName());

                messageRecord.append(message1.getFromName()+"对小爱说"+" : "+message1.getMessage()+" -- "+sdf.format(new Date())+"/++/");

                messageRecord.append("小爱对 :"+toMessage.getToName()+"说"+toMessage.getMessage()+" /+++ "+sdf.format(new Date())+"/++/");

                this.session.getBasicRemote().sendText(JsonMessage(true,toMessage,null));
            }else{
                Chat chat = clients.get(message1.getToName());
                messageRecord.append(message1.getFromName()+"对"+message1.getToName()+"说"+" : "+message1.getMessage()+" /+++ "+sdf.format(new Date())+"/++/");
                chat.session.getBasicRemote().sendText(JsonMessage(true,message1,null));
            }

        }
    }


    /**
     * 错误处理
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("WebSocket发生错误：" + throwable.getMessage());
    }

    public static void sendMessage(String message) {
        // 向所有连接websocket的客户端发送消息
        // 可以修改为对某个客户端发消息
        for (Chat item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }



    /**
     * 消息的封装
     * @param system true为普通消息    false为系统消息
     * @param message   普通消息封装
     * @param info 系统消息封装
     * @return
     */
    public String JsonMessage(boolean system, Message message,Object info){
        if (system){
            Result resultMessage=new Result(true, StatusCode.OK,"普通消息",message);
            return JSON.toJSONString(resultMessage);
        }else{
            Result resultMessage=new Result(false, StatusCode.OK,"系统消息",info);
            return JSON.toJSONString(resultMessage);
        }
    }



}
